package com.njtoyo.taxi.admin.service.business.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.njtoyo.taxi.admin.library.common.Enum;
import com.njtoyo.taxi.admin.library.common.OperationRecordHelper;
import com.njtoyo.taxi.admin.logic.business.RechargeLogic;
import com.njtoyo.taxi.admin.logic.business.ride.AccountLogic;
import com.njtoyo.taxi.admin.logic.business.ride.RideOrderLogic;
import com.njtoyo.taxi.admin.logic.business.simple_call.RideTransactionLogLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.*;
import com.njtoyo.taxi.admin.mapper.master.enums.DesignatedCallState;
import com.njtoyo.taxi.admin.mapper.master.enums.DesignatedRideState;
import com.njtoyo.taxi.admin.mapper.master.enums.DriverFlowLogCategory;
import com.njtoyo.taxi.admin.mapper.master.mapper.*;
import com.njtoyo.taxi.admin.rest.presenter.business.ride.*;
import com.njtoyo.taxi.admin.rest.wrapper.business.ride.DesignatedRideQueryWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.business.ride.OrderManageQueryDto;
import com.njtoyo.taxi.admin.rest.wrapper.business.ride.UpdateOrderAmountWrapper;
import com.njtoyo.taxi.admin.service.business.DesignatedService;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author mdf
 * @title: DesignatedServiceImpl
 * @description: TODO
 * @date 2024/3/5 10:11
 */
@Service
@Slf4j
public class DesignatedServiceImpl implements DesignatedService {

    @Autowired
    private DesignatedCallMapper designatedCallMapper;
    @Autowired
    private DesignatedCallRideMapper designatedCallRideMapper;
    @Autowired
    private DesignatedCallRideOrderMapper designatedCallRideOrderMapper;
    @Autowired
    private DesignatedCallRideStateMapper designatedCallRideStateMapper;
    @Autowired
    private DesignatedCallRideLocateMapper designatedCallRideLocateMapper;
    @Autowired
    private DesignatedCallRideCancellationMapper designatedCallRideCancellationMapper;
    @Autowired
    private DesignatedCallRideCancellationOrderMapper designatedCallRideCancellationOrderMapper;
    @Autowired
    private OperationRecordHelper operationRecordHelper;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GeoAreaMapper geoAreaMapper;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private GeoCantonMapper geoCantonMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private DriverScoreDeductingMapper driverScoreDeductingMapper;
    @Autowired
    private CustomerCancelReasonLogMapper customerCancelReasonLogMapper;
    @Autowired
    private CustomerCancelReasonOptionMapper customerCancelReasonOptionMapper;
    @Autowired
    private CallPaymentMapper callPaymentMapper;
    @Autowired
    private RideOrderLogic rideOrderLogic;
    @Autowired
    private RechargeLogic rechargeLogic;
    @Autowired
    private RideTransactionLogLogic rideTransactionLogLogic;
    @Autowired
    private RechargeMapper rechargeMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AccountLogic accountLogic;

    @Override
    public RestResult getList(AdminUser adminUser, DesignatedRideQueryWrapper wrapper) {
        if (StrUtil.isNotBlank(wrapper.getState())) {
            if ("nopick".equals(wrapper.getState())) wrapper.setCallState(DesignatedCallState.nopick);
            if ("cancelled".equals(wrapper.getState())) wrapper.setCallState(DesignatedCallState.cancelled);
            if ("covered".equals(wrapper.getState())) wrapper.setCallState(DesignatedCallState.covered);
            if ("pick_up".equals(wrapper.getState())) wrapper.setRideState(DesignatedRideState.pick_up);
            if ("in_area".equals(wrapper.getState())) wrapper.setRideState(DesignatedRideState.in_area);
            if ("start".equals(wrapper.getState())) wrapper.setRideState(DesignatedRideState.start);
            if ("end".equals(wrapper.getState())) wrapper.setRideState(DesignatedRideState.end);
            if ("paid".equals(wrapper.getState())) wrapper.setRideState(DesignatedRideState.paid);
        }
        if (StrUtil.isNotBlank(wrapper.getStartDate()) && StrUtil.isNotBlank(wrapper.getEndDate())) {
            wrapper.setStartDate(DateUtil.beginOfDay(DateUtil.parseDate(wrapper.getStartDate())).toString());
            wrapper.setEndDate(DateUtil.endOfDay(DateUtil.parseDate(wrapper.getEndDate())).toString());
        }
        IPage<DesignatedListPresenterDTO> page = designatedCallMapper.getDesignatedPage(new Page<>(wrapper.getCurrent(), wrapper.getSize()), wrapper);

        List<DesignatedRideListPresenter> listPresenters = new ArrayList<>();
        for (DesignatedListPresenterDTO dto : page.getRecords()) {
            DesignatedRideListPresenter rideListPresenter = new DesignatedRideListPresenter();
            rideListPresenter.setUser(new RideListPresenter.User().setId(dto.getUserId()).setMobileNumber(dto.getUserMobileNumber()).setName(dto.getUserName()));
            rideListPresenter.setDriver(new RideListPresenter.Driver().setId(dto.getDriverId()).setMobileNumber(dto.getDriverMobileNumber()).setName(dto.getDriverName()));
            rideListPresenter.setTaxi(new RideListPresenter.Taxi().setPlateNumber(dto.getPlateNumber()));
            rideListPresenter.setId(dto.getId());
            rideListPresenter.setPlatform(dto.getPlatform());
            rideListPresenter.setCategory(dto.getCategory());
            rideListPresenter.setCreatedAt(dto.getCreatedAt());
            rideListPresenter.setOriginName(dto.getOriginName());
            rideListPresenter.setCallOriginName(dto.getCallOriginName());
            rideListPresenter.setDestinationName(dto.getDestinationName());
            rideListPresenter.setCallDestinationName(dto.getCallDestinationName());
            rideListPresenter.setArea(new RideListPresenter.Area().setName(dto.getAreaName()));
            DesignatedRideListPresenter.RideOrder rideOrder = new DesignatedRideListPresenter.RideOrder().setId(dto.getRideOrderId()).setAmount(dto.getRideOrderAmount())
                    .setPaidThrough(dto.getRideOrderPaidThrough())
                    .setPresetThrough(dto.getRideOrderPresetThrough())
                    .setRefunded(dto.getRideOrderRefunded())
                    .setIsPaid(dto.getIsPaid());
            if (dto.getCallState() != DesignatedCallState.pick) {
                rideListPresenter.setState(dto.getCallState().name());
            } else {
                rideListPresenter.setState(dto.getRideState().name());
            }
            rideListPresenter.setRideOrder(rideOrder);
            listPresenters.add(rideListPresenter);
        }
        IPage<DesignatedRideListPresenter> pages = new Page<>();
        pages.setCurrent(page.getCurrent());
        pages.setPages(page.getPages());
        pages.setSize(page.getSize());
        pages.setTotal(page.getTotal());
        pages.setRecords(listPresenters);
        return RestResult.success(pages);
    }

    @Override
    public RestResult<Boolean> updateOrderAmount(Long id, UpdateOrderAmountWrapper wrapper) {
        DesignatedCallRide ride = designatedCallRideMapper.selectOne(Wrappers.<DesignatedCallRide>lambdaQuery()
                .eq(DesignatedCallRide::getRefId, id));
        if (ObjectUtil.isNull(ride)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        // 判断ride是否处于完成待付款状态
        if (DesignatedRideState.paid.equals(ride.getState())) {
            return RestResult.failed("此行程未处于待付款状态");
        }
        DesignatedCallRideOrder rideOrder = designatedCallRideOrderMapper.selectOne(Wrappers.<DesignatedCallRideOrder>lambdaQuery().eq(DesignatedCallRideOrder::getRideId, ride.getId()));
        if (ObjectUtil.isNotNull(rideOrder)) {
            String number = "DRO" + IdUtil.getSnowflake(1, 1).nextIdStr();
            designatedCallRideOrderMapper.updateById(new DesignatedCallRideOrder().setId(rideOrder.getId())
                    .setNumber(number)
                    .setAmount(wrapper.getAmount()));
            callPaymentMapper.update(new CallPayment().setAmount(wrapper.getAmount()).setNumber(number),
                    Wrappers.<CallPayment>lambdaUpdate().eq(CallPayment::getRefId, rideOrder.getId()));
            operationRecordHelper.addBusinessLog(String.format("修改未付款代驾订单金额，行程id [%d]，金额 [%f]", id, wrapper.getAmount()));
        }


        return RestResult.success();
    }

    @Override
    public RestResult getTrack(Long callId) {
        DesignatedCallRide ride = designatedCallRideMapper.selectOne(Wrappers.<DesignatedCallRide>lambdaQuery().eq(DesignatedCallRide::getRefId, callId));
        if (ObjectUtil.isNull(ride)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        RideTrackPresenter res = new RideTrackPresenter();
        res.setId(ride.getId());
        res.setCallOrigin(ride.getOrigin());
        res.setCallDestination(ride.getDestination());

        List<DesignatedCallRideState> rideStateList = new LambdaQueryChainWrapper<>(designatedCallRideStateMapper)
                .eq(DesignatedCallRideState::getRideId, ride.getId()).list();

        if (CollUtil.isNotEmpty(rideStateList)) {
            // 司机接单点
            Optional<DesignatedCallRideState> pick_up_pickuping = rideStateList.stream().filter(i -> i.getState().equals(DesignatedRideState.pick_up)).findFirst();
            pick_up_pickuping.ifPresent(rideState -> res.setPickUp(rideState.getLocate()));

            // 实际乘客上车点
            Optional<DesignatedCallRideState> origin = rideStateList.stream().filter(i -> i.getState().equals(DesignatedRideState.start)).findFirst();
            origin.ifPresent(rideState -> res.setOrigin(rideState.getLocate()));

            // 实际乘客下车点
            Optional<DesignatedCallRideState> destination = rideStateList.stream().filter(i -> i.getState().equals(DesignatedRideState.end)).findFirst();
            destination.ifPresent(rideState -> res.setDestination(rideState.getLocate()));
        }

        List<DesignatedCallRideLocate> rideLocateList = new LambdaQueryChainWrapper<>(designatedCallRideLocateMapper).select(DesignatedCallRideLocate::getLocate).eq(DesignatedCallRideLocate::getRideId, ride.getId()).list();

        if (ObjectUtil.isNotEmpty(rideLocateList)) {
            res.setRideLocateLog(rideLocateList.stream().map(DesignatedCallRideLocate::getLocate).collect(Collectors.toList()));
        }
        return RestResult.success(res);
    }

    @Override
    public RestResult getRideDetail(Long callId) {
        DesignatedCall call = designatedCallMapper.selectById(callId);
        if (ObjectUtil.isEmpty(call)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        DesignatedCallRide ride = designatedCallRideMapper.selectOne(Wrappers.<DesignatedCallRide>lambdaQuery().eq(DesignatedCallRide::getRefId, callId));
        if (ObjectUtil.isEmpty(ride)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        DesignatedRideDetailPresenter res = BeanUtil.copyProperties(ride, DesignatedRideDetailPresenter.class);

        // driver
        if (Objects.nonNull(ride.getDriverId())) {
            Driver driver = new LambdaQueryChainWrapper<>(driverMapper).select(Driver::getId, Driver::getName, Driver::getMobileNumber).eq(Driver::getId, ride.getDriverId()).one();
            if (Objects.nonNull(driver)) {
                res.setDriver(BeanUtil.copyProperties(driver, DesignatedRideDetailPresenter.Driver.class));
            }
        }


        // user
        if (Objects.nonNull(ride.getCustomerId())) {
            User user = new LambdaQueryChainWrapper<>(userMapper).select(User::getId, User::getName, User::getMobileNumber).eq(User::getId, ride.getCustomerId()).one();
            if (Objects.nonNull(user)) {
                res.setUser(BeanUtil.copyProperties(user, DesignatedRideDetailPresenter.User.class));
            }
        }

        // area
        if (Objects.nonNull(ride.getAreaId())) {
            GeoArea area = new LambdaQueryChainWrapper<>(geoAreaMapper).select(GeoArea::getId, GeoArea::getName, GeoArea::getCityId).eq(GeoArea::getId, ride.getAreaId()).one();
            if (Objects.nonNull(area)) {
                res.setArea(BeanUtil.copyProperties(area, DesignatedRideDetailPresenter.Area.class));

                // city
                if (Objects.nonNull(area.getCityId())) {
                    City city = new LambdaQueryChainWrapper<>(cityMapper).select(City::getId, City::getName).eq(City::getId, area.getCityId()).one();
                    if (Objects.nonNull(city)) {
                        res.setCity(BeanUtil.copyProperties(city, DesignatedRideDetailPresenter.City.class));
                    }
                }
            }
        }

        // canton
        if (Objects.nonNull(ride.getCantonId())) {
            GeoCanton canton = new LambdaQueryChainWrapper<>(geoCantonMapper).select(GeoCanton::getId, GeoCanton::getName).eq(GeoCanton::getId, ride.getCantonId()).one();
            if (Objects.nonNull(canton)) {
                res.setCanton(BeanUtil.copyProperties(canton, DesignatedRideDetailPresenter.Canton.class));
            }
        }

        // ride_order
        DesignatedCallRideOrder ride_order = new LambdaQueryChainWrapper<>(designatedCallRideOrderMapper).in(DesignatedCallRideOrder::getRideId, ride.getId()).one();

        if (Objects.nonNull(ride_order)) {
            DesignatedRideDetailPresenter.RideOrder rideOrder = BeanUtil.copyProperties(ride_order, DesignatedRideDetailPresenter.RideOrder.class);
            // coupon
            if (Objects.nonNull(ride_order.getCouponId())) {
                Coupon coupon = new LambdaQueryChainWrapper<>(couponMapper).select(Coupon::getId, Coupon::getCategory, Coupon::getDigit, Coupon::getLimitation).eq(Coupon::getId, ride_order.getCouponId()).one();
                rideOrder.setCoupon(BeanUtil.copyProperties(coupon, DesignatedRideDetailPresenter.Coupon.class));
            }

            CallPayment callPayment = new LambdaQueryChainWrapper<>(callPaymentMapper).in(CallPayment::getRefId, ride_order.getId()).one();
            if (ObjectUtil.isNotNull(callPayment)) {
                rideOrder.setCallPayment(BeanUtil.copyProperties(callPayment, CallPayment.class));
            }
            res.setRideOrder(rideOrder);
        }


        // ride_state
        List<DesignatedCallRideState> rideStateList = new LambdaQueryChainWrapper<>(designatedCallRideStateMapper).eq(DesignatedCallRideState::getRideId, ride.getId()).list();
        if (ObjectUtil.isNotEmpty(rideStateList)) {
            List<DesignatedRideDetailPresenter.RideStateLog> rideStateLogList = new ArrayList<>();
            rideStateList.forEach(i -> {
                DesignatedRideDetailPresenter.RideStateLog rideStateLog = BeanUtil.copyProperties(i, DesignatedRideDetailPresenter.RideStateLog.class);
                rideStateLogList.add(rideStateLog);
            });

            res.setRideStateLog(rideStateLogList);
        }

        // ride_cancellation
        DesignatedCallRideCancellation ride_cancellation = new LambdaQueryChainWrapper<>(designatedCallRideCancellationMapper).select(DesignatedCallRideCancellation::getId, DesignatedCallRideCancellation::getRideId, DesignatedCallRideCancellation::getTriggerBy, DesignatedCallRideCancellation::getCreatedAt, DesignatedCallRideCancellation::getUpdatedAt).eq(DesignatedCallRideCancellation::getRideId, ride.getId()).one();

        if (Objects.nonNull(ride_cancellation)) {
            DesignatedRideDetailPresenter.RideCancellation rideCancellation = BeanUtil.copyProperties(ride_cancellation, DesignatedRideDetailPresenter.RideCancellation.class);

            DesignatedCallRideCancellationOrder cancellationOrder = new LambdaQueryChainWrapper<>(designatedCallRideCancellationOrderMapper).eq(DesignatedCallRideCancellationOrder::getCancelId, ride_cancellation.getId()).one();

            // cancellation_order
            if (Objects.nonNull(cancellationOrder)) {
                DesignatedRideDetailPresenter.CancellationOrder cancellationOrderSub = BeanUtil.copyProperties(cancellationOrder, DesignatedRideDetailPresenter.CancellationOrder.class);
                rideCancellation.setCancellationOrder(cancellationOrderSub);
            }

            // driver_score_deduct
            DriverScoreDeducting driverScoreDeducting = new LambdaQueryChainWrapper<>(driverScoreDeductingMapper).select(DriverScoreDeducting::getId, DriverScoreDeducting::getDeduction, DriverScoreDeducting::getStartedAt, DriverScoreDeducting::getEndedAt).eq(DriverScoreDeducting::getReferenceId, ride_cancellation.getId()).one();

            if (Objects.nonNull(driverScoreDeducting)) {
                DesignatedRideDetailPresenter.DriverScoreDeduct driverScoreDeductingSub = BeanUtil.copyProperties(driverScoreDeducting, DesignatedRideDetailPresenter.DriverScoreDeduct.class);
                rideCancellation.setDriverScoreDeduct(driverScoreDeductingSub);
            }

            res.setRideCancellation(rideCancellation);

            // customer_cancel_reason_log
            CustomerCancelReasonLog customer_cancel_reason_log = new LambdaQueryChainWrapper<>(customerCancelReasonLogMapper).select(CustomerCancelReasonLog::getId, CustomerCancelReasonLog::getReason, CustomerCancelReasonLog::getCreatedAt, CustomerCancelReasonLog::getUpdatedAt, CustomerCancelReasonLog::getRefId).eq(CustomerCancelReasonLog::getRideId, ride.getId()).one();

            if (Objects.nonNull(customer_cancel_reason_log)) {
                DesignatedRideDetailPresenter.CustomerCancelReasonLog customerCancelReasonLog = BeanUtil.copyProperties(customer_cancel_reason_log, DesignatedRideDetailPresenter.CustomerCancelReasonLog.class);
                // reasonOption
                CustomerCancelReasonOption customerCancelReasonOption = new LambdaQueryChainWrapper<>(customerCancelReasonOptionMapper).select(CustomerCancelReasonOption::getId, CustomerCancelReasonOption::getCategory, CustomerCancelReasonOption::getReason).eq(CustomerCancelReasonOption::getId, customer_cancel_reason_log.getRefId()).one();
                if (Objects.nonNull(customerCancelReasonOption)) {
                    DesignatedRideDetailPresenter.ReasonOption customerCancelReasonOptionSub = BeanUtil.copyProperties(customerCancelReasonOption, DesignatedRideDetailPresenter.ReasonOption.class);
                    customerCancelReasonLog.setReasonOption(customerCancelReasonOptionSub);
                }

                res.setCustomerCancelReasonLog(customerCancelReasonLog);
            }
        }
        if (call.getState() != DesignatedCallState.pick) {
            res.setState(call.getState().name());
        } else {
            res.setState(ride.getState().name());
        }
        res.setCallInfo(call);

        return RestResult.success(res);
    }

    @Override
    public RestResult<Boolean> orderRefund(Long callId) {
        log.info("开始执行代驾退款操作,callId:{}", callId);
        DesignatedCallRide ride = designatedCallRideMapper.selectOne(Wrappers.<DesignatedCallRide>lambdaQuery().eq(DesignatedCallRide::getRefId, callId));
        if (ObjectUtil.isEmpty(ride)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        // 判断该行程是否存在已付款的订单
        DesignatedCallRideOrder rideOrder = designatedCallRideOrderMapper.selectOne(Wrappers.<DesignatedCallRideOrder>lambdaQuery()
                .eq(DesignatedCallRideOrder::getRideId, ride.getId())
                .eq(DesignatedCallRideOrder::getIsPaid, Boolean.TRUE));
        if (ObjectUtil.isNull(rideOrder)) {
            return RestResult.failed("此行程没有已付款订单");
        }
        // 订单已退款
        if (rideOrder.getRefunded()) {
            return RestResult.failed("此行程订单在本操作前已被退款");
        }
        log.info(String.format("开始行程退款，行程ID [%d]", ride.getId()));
        RideOrder order = new RideOrder();
        order.setUserId(rideOrder.getCustomerId());
        order.setAmount(rideOrder.getAmount());
        order.setNumber(rideOrder.getNumber());
        order.setFarePaid(rideOrder.getCustomerFarePaid());
        order.setId(rideOrder.getId());
        // 检查行程订单是否已拥有初始化过的退款记录，如果发现拥有已完成的退款记录，则抛出异常
        // 订单不含有初始化的退款记录
        if (!rideOrderLogic.checkInitializedDesignatedRefund(rideOrder.getId())) {
            rideOrderLogic.initRefund(order, "RideOrder");
        }

        // 订单不含实付金额
        if (ObjectUtil.isNull(rideOrder.getCustomerFarePaid())) {
            return RestResult.failed("退款失败,订单无实际支付金额");
        }
        // 发起招商微信小程序退款
        Boolean thirdPayRefundSuccess = rideOrderLogic.initiateJrcbWeChatRefund(order, Enum.RideRefundWxAppType.wxmina);

        // //第三方支付退款成功，继续做余额退款和状态修改
        if (thirdPayRefundSuccess) {
            // 订单含有余额支付金额
            if (rideOrderLogic.hasSavingPaid(order)) {
                log.info("[service]:订单含有余额支付金额");
                rechargeLogic.updateRefundedByOrderId(rideOrder.getId());
                RideTransactionLog rideTransactionLog = rideTransactionLogLogic.getLogByRideOrderId(rideOrder.getId());

                BigDecimal paySavingPaidAmount = BigDecimal.ZERO;
                BigDecimal donationSavingPaidAmount = BigDecimal.ZERO;

                if (Objects.nonNull(rideTransactionLog)) {
                    Recharge recharge = rechargeMapper.selectById(rideTransactionLog.getRechargeId());
                    paySavingPaidAmount = rideOrderLogic.getPaySavingPaidAmount(recharge);
                    donationSavingPaidAmount = rideOrderLogic.getDonationSavingPaidAmount(recharge);
                }

                Account account = accountLogic.getByCustomerId(rideOrder.getCustomerId());
                if (Objects.isNull(account)) {
                    return RestResult.failed("乘客账户信息错误");
                }

                boolean updateAccount = new LambdaUpdateChainWrapper<>(accountMapper).eq(Account::getId, account.getId()).set(Account::getAmount, NumberUtil.add(account.getAmount(), paySavingPaidAmount, donationSavingPaidAmount)).set(Account::getPayAmount, NumberUtil.add(account.getPayAmount(), paySavingPaidAmount)).set(Account::getDonationAmount, NumberUtil.add(account.getDonationAmount(), donationSavingPaidAmount)).set(Account::getUpdatedAt, new Date()).update();
            } else {
                log.info("[service]:订单没有余额支付金额");
            }


            // 删除对应司机收入流水
            log.info("删除对应司机收入流水[开始]");
            rideOrderLogic.deleteDriverFlowLogByOrderId(rideOrder.getId(), DriverFlowLogCategory.designated_call_ride_order);
            log.info("删除对应司机收入流水[结束]");

            // 删除对应公司分成流水
            log.info("删除对应公司分成流水[开始]");
            rideOrderLogic.deleteIncomeBelongingLogByOrderId(rideOrder.getId());
            log.info("删除对应公司分成流水[结束]");

            // 修改 refund
            boolean updateRefund = rideOrderLogic.updateRefundStateDoneByOrderId(rideOrder.getId());
            log.info("修改 refund 状态");

            // 修改 rideOrder
            boolean updateOrder = new LambdaUpdateChainWrapper<>(designatedCallRideOrderMapper).eq(DesignatedCallRideOrder::getId, rideOrder.getId()).set(DesignatedCallRideOrder::getRefunded, true).update();
            log.info("修改 rideOrder 状态");

            operationRecordHelper.addBusinessLog(String.format("行程订单退款,行程id: [%d]", ride.getId()));

            return RestResult.success(updateRefund && updateOrder);
        }

        return RestResult.failed("操作失败");
    }

    @Override
    public List<OrderManageVo> getProxyDrivingList(AdminUser adminUser, OrderManageQueryDto wrapper) {
        List<OrderManageVo> list = new ArrayList<>();
        if (StrUtil.isNotBlank(wrapper.getOrderState())) {
            if ("nopick".equals(wrapper.getState())) wrapper.setCallState(DesignatedCallState.nopick);
            if ("cancelled".equals(wrapper.getState())) wrapper.setCallState(DesignatedCallState.cancelled);
            if ("covered".equals(wrapper.getState())) wrapper.setCallState(DesignatedCallState.covered);
            if ("pick_up".equals(wrapper.getState())) wrapper.setRideState(DesignatedRideState.pick_up);
            if ("in_area".equals(wrapper.getState())) wrapper.setRideState(DesignatedRideState.in_area);
            if ("start".equals(wrapper.getState())) wrapper.setRideState(DesignatedRideState.start);
            if ("end".equals(wrapper.getState())) wrapper.setRideState(DesignatedRideState.end);
            if ("paid".equals(wrapper.getState())) wrapper.setRideState(DesignatedRideState.paid);
        }
        if (null != wrapper.getStartDate() && null != wrapper.getEndDate()) {
            wrapper.setStartDate(DateUtil.beginOfDay(wrapper.getStartDate()));
            wrapper.setEndDate(DateUtil.endOfDay(wrapper.getEndDate()));
        }
        List<DesignatedListPresenterDTO> designatedList = designatedCallMapper.getDesignatedList(wrapper);
        if (CollUtil.isNotEmpty(designatedList)) {
            for (DesignatedListPresenterDTO designatedListPresenterDTO : designatedList) {
                OrderManageVo vo  = new OrderManageVo();
                vo.setId(designatedListPresenterDTO.getId());
                vo.setTabName("代驾");
                //平台
                vo.setPlatform(designatedListPresenterDTO.getPlatform().getDesc());
                vo.setCategory(designatedListPresenterDTO.getCategory().getDesc());
                vo.setOrderId(designatedListPresenterDTO.getId().toString());
                //司机
                if(null != designatedListPresenterDTO.getDriverId()){
                    vo.setDriverId(designatedListPresenterDTO.getDriverId().toString());
                    vo.setDriverName(designatedListPresenterDTO.getDriverName());
                    vo.setDriverPhoneNumber(designatedListPresenterDTO.getDriverMobileNumber());
                }
                //车牌
                vo.setVehicleNumber(designatedListPresenterDTO.getPlateNumber());
                //乘客
                if(null != designatedListPresenterDTO.getUserId()){
                    vo.setPassengerId(designatedListPresenterDTO.getUserId().toString());
                    vo.setPassengerName(designatedListPresenterDTO.getUserName());
                    vo.setPassengerPhoneNumber(designatedListPresenterDTO.getUserMobileNumber());
                }
                //下单时间
                vo.setOrderTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(designatedListPresenterDTO.getCreatedAt()));
                if(StringUtils.isNotBlank(designatedListPresenterDTO.getAreaName())){
                    vo.setAreaName(designatedListPresenterDTO.getAreaName());
                }
                //上下车
                if(StringUtils.isNotBlank(designatedListPresenterDTO.getCallOriginName())){
                    vo.setCallOriginName(designatedListPresenterDTO.getCallOriginName());
                }
                if(StringUtils.isNotBlank(designatedListPresenterDTO.getCallDestinationName())){
                    vo.setCallDestinationName(designatedListPresenterDTO.getCallDestinationName());
                }
                if(StringUtils.isNotBlank(designatedListPresenterDTO.getDestinationName())){
                    vo.setDestinationName(designatedListPresenterDTO.getDestinationName());
                }
                if(StringUtils.isNotBlank(designatedListPresenterDTO.getOriginName())){
                    vo.setOriginName(designatedListPresenterDTO.getOriginName());
                }

                //支付信息
                if(null != designatedListPresenterDTO.getIsPaid())
                {
                    if(designatedListPresenterDTO.getIsPaid()){
                        if(designatedListPresenterDTO.getRideOrderRefunded()){
                            vo.setPaidState("已退款");
                        }else{
                            vo.setPaidState("已支付");
                        }
                        if(null != designatedListPresenterDTO.getRideOrderPaidThrough()){
                            vo.setPaidThrough(designatedListPresenterDTO.getRideOrderPaidThrough().getDesc());
                            vo.setAmount(designatedListPresenterDTO.getRideOrderAmount());
                        }
                    }
                }

                //订单状态
                if (designatedListPresenterDTO.getCallState() != DesignatedCallState.pick) {

                    if(null != designatedListPresenterDTO.getCallState()){
                        vo.setOrderState(designatedListPresenterDTO.getCallState().getDesc());
                        if(0 == designatedListPresenterDTO.getCallState().getCode()){
                            vo.setOrderStateEn("nopick");
                        }else if(1 == designatedListPresenterDTO.getCallState().getCode())
                        {
                            vo.setOrderStateEn("pick");
                        }else if(2 == designatedListPresenterDTO.getCallState().getCode())
                        {
                            vo.setOrderStateEn("cancelled");
                        }else if(3 == designatedListPresenterDTO.getCallState().getCode())
                        {
                            vo.setOrderStateEn("covered");
                        }
                    }
                } else {
                    if(null != designatedListPresenterDTO.getRideState()){
                        vo.setOrderState(designatedListPresenterDTO.getRideState().getDesc());
                        if(0 == designatedListPresenterDTO.getRideState().getCode()){
                            vo.setOrderStateEn("pick_up");
                        }else if(1 == designatedListPresenterDTO.getRideState().getCode())
                        {
                            vo.setOrderStateEn("in_area");
                        }else if(2 == designatedListPresenterDTO.getRideState().getCode())
                        {
                            vo.setOrderStateEn("start");
                        }else if(3 == designatedListPresenterDTO.getRideState().getCode())
                        {
                            vo.setOrderStateEn("end");
                        }else if(4 == designatedListPresenterDTO.getRideState().getCode())
                        {
                            vo.setOrderStateEn("paid");
                        }
                    }
                }
                list.add(vo);
            }
        }
        return list;
    }
}
